package com.sugon.controller.module;

import cn.afterturn.easypoi.entity.vo.TemplateExcelConstants;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.view.PoiBaseView;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.annotation.AutoLog;
import com.sugon.entity.ModulPositionCorrelationEntity;
import com.sugon.entity.ModuleArchivesEntity;
import com.sugon.entity.MoldTypePositionEntity;
import com.sugon.modules.mold.model.MoldCorrPositionCostStatVO;
import com.sugon.modules.mold.model.MoldCostStatVO;
import com.sugon.service.ModulPositionCorrelationService;
import com.sugon.service.ModuleArchivesService;
import com.sugon.service.ModuleTypePositionService;
import com.sugon.service.SysConfigService;
import com.sugon.utils.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 模具位置关联Controller
 *
 * @author sugon
 * @date 2019-08-08 17:47:30
 */
@Controller
@RequestMapping("modulpositioncorrelation")
public class ModulPositionCorrelationController {
    @Autowired
    private ModulPositionCorrelationService moldPositionService;
    @Autowired
    private SysConfigService configService;
    @Resource
    private ModuleTypePositionService moldTypePositionService;
    @Resource
    private ModuleArchivesService moldService;

    /**
     * 查看备件单位列表
     */
    @RequestMapping("/listUnit")
    @ResponseBody
    public R getSparePartUnitList() {
        String sparePartUnit = configService.getValue("MOLD_POSITION_TYPE", "");
        return R.ok().put("moldPositionTypes", sparePartUnit.split(","));
    }

    /**
     * 模具成本(年度)统计
     * 具体列出模具关联的所有位置年度平均统计
     */
    @RequestMapping("/moduleCostStat")
    @ResponseBody
    public R moduleCostStat(@RequestParam Map<String, Object> params) {
        // 模具编码必填
        String moduleCode = MapUtil.getStr(params, "moduleCode");
        // 模具号必填
        String moduleNo = MapUtil.getStr(params, "moduleNo");
        if (StrUtil.isEmpty(moduleCode) && StrUtil.isEmpty(moduleNo)) {
            return R.error("模具必选");
        }
        // 默认查询当年的
        String year = MapUtil.getStr(params, "year", DateUtil.thisYear() + "");

        //查询列表数据
        Query query = new Query(params);
        // 查询模具成本统计
        List<MoldCostStatVO> costStatList = moldPositionService.moduleCostStat(moduleNo, moduleCode, year);
        PageUtils pageUtil = new PageUtils(costStatList, costStatList.size(), query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 模具某个关联位置的成本统计
     * 具体是指定年度的某个模具关联位置的各个月份的统计数据
     */
    @RequestMapping("/costStat")
    @ResponseBody
    public R costStat(@RequestParam Map<String, Object> params) {
        // 模具关联位置ID必填
        String id = MapUtil.getStr(params, "id");
        if (StrUtil.isEmpty(id)) {
            return R.error("模具关联位置必选");
        }
        String year = MapUtil.getStr(params, "year", "");

        //查询列表数据
        Query query = new Query(params);
        List<MoldCorrPositionCostStatVO> modulPositionCorrelationList = moldPositionService.costStat(id, year);
        PageUtils pageUtil = new PageUtils(modulPositionCorrelationList, modulPositionCorrelationList.size(), query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("modulpositioncorrelation:list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) {
        String moldId = cn.hutool.core.map.MapUtil.getStr(params, "moldId");
        if (StrUtil.isEmpty(moldId)) {
            return R.error("模具必选！");
        }
        /*
            尝试获取指定模具的位置列表。
            如果为空，有两种情况
            1、这幅模具确实没有设置关联模具位置，则默认拉取对应类型下已关联的位置
            2、这幅模具已设置关联位置，但是满足条件的没有，不做任何处理
         */
        Query query = new Query(params);
        List<ModulPositionCorrelationEntity> modulPositionCorrelationList = moldPositionService.queryList(query);
        if (CollectionUtil.isEmpty(modulPositionCorrelationList)) {
            List<ModulPositionCorrelationEntity> moldPositionList = moldPositionService.queryListByMoldId(moldId);
            if (CollectionUtil.isEmpty(moldPositionList)) {
                ModuleArchivesEntity mold = moldService.queryObject(moldId);
                if (mold != null) {
                    String moldType = mold.getModuleType();
                    List<MoldTypePositionEntity> positionList = moldTypePositionService.queryList(moldType);
                    if (CollectionUtil.isNotEmpty(positionList)) {
                        ModulPositionCorrelationEntity moldPos;
                        for (MoldTypePositionEntity pos : positionList) {
                            moldPos = new ModulPositionCorrelationEntity(moldId, pos.getId());
                            moldPositionService.save(moldPos);
                        }
                        // 重新再查询一次
                        modulPositionCorrelationList = moldPositionService.queryList(query);
                    }
                }
            }
        }
        int total = moldPositionService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(modulPositionCorrelationList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("modulpositioncorrelation:info")
    @ResponseBody
    public R info(@PathVariable("id") String id) {
        ModulPositionCorrelationEntity modulPositionCorrelation = moldPositionService.queryObject(id);

        return R.ok().put("modulPositionCorrelation", modulPositionCorrelation);
    }

    /**
     * 保存
     */
    @AutoLog("模具位置关联--保存")
    @RequestMapping("/save")
    @RequiresPermissions("modulpositioncorrelation:save")
    @ResponseBody
    public R save(@RequestBody ModulPositionCorrelationEntity modulPositionCorrelation) {
        moldPositionService.save(modulPositionCorrelation);

        return R.ok();
    }

    /**
     * 修改
     */
    @AutoLog("模具位置关联--修改")
    @RequestMapping("/update")
    @RequiresPermissions("modulpositioncorrelation:update")
    @ResponseBody
    public R update(@RequestBody ModulPositionCorrelationEntity modulPositionCorrelation) {
        moldPositionService.update(modulPositionCorrelation);

        return R.ok();
    }

    /**
     * 删除
     */
    @AutoLog("模具位置关联--删除")
    @RequestMapping("/delete")
    @RequiresPermissions("modulpositioncorrelation:delete")
    @ResponseBody
    public R delete(@RequestBody String[] ids) {
        moldPositionService.deleteBatch(ids);

        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    @RequiresPermissions("modulpositioncorrelation:list")
    @ResponseBody
    public R queryAll(@RequestParam Map<String, Object> params) {

        List<ModulPositionCorrelationEntity> list = moldPositionService.queryList(params);

        return R.ok().put("list", list);
    }

    @RequestMapping("/export")
    @ResponseBody
    @AutoLog("执行导出数据")
    public void export(@RequestParam Map<String, Object> queryParam, ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) {
        // 设置导出EXCEL模板名称
        modelMap.put(TemplateExcelConstants.FILE_NAME, "模具位置关联导出_" + DateUtil.format(DateUtil.date(), "yyyyMMdd"));
        // 设置导出模板参数
        TemplateExportParams templateExportParams = new TemplateExportParams(configService.getPoiTemplatePath() + "moldPositionCorrelationTemplate.xlsx");
        templateExportParams.setColForEach(true);
        modelMap.put(TemplateExcelConstants.PARAMS, templateExportParams);
        // 获取设备维护计划预览模板数据
        Map<String, Object> mapData = cn.hutool.core.map.MapUtil.newHashMap(1);
        // 获取预防性维护计划数据
        mapData.put("list", moldPositionService.queryList(queryParam));
        modelMap.put(TemplateExcelConstants.MAP_DATA, mapData);
        PoiBaseView.render(modelMap, request, response, TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);
    }

    /**
     * 导入或更新模具关联位置信息
     */
    @RequestMapping("/import")
    @ResponseBody
    public R importE(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        int count = moldPositionService.importE(file);
        return R.ok("成功导入或更新" + count + "条数据");
    }

}
